<template>
  <a-modal v-model:open="open" :title="fromModel.id?'编辑':'新增'"
           cancel-text="取消"
           :confirm-loading="confirmLoading" @ok="handleOk" @cancel="close">
    <div>
      <a-form
          ref="formRef"
          :model="fromModel"
          :rules="rules"
          :label-col="{ span: 5 }"
      >
      <a-form-item label="分类名称" name="name">
          <a-input v-model:value="fromModel.name"
                   placeholder="分类名称"
                   allow-clear/>
      </a-form-item>
      <a-form-item label="排序" name="sort">
          <a-input-number v-model:value="fromModel.sort"
                   placeholder="排序"
                   allow-clear/>
      </a-form-item>
    
      </a-form>
    </div>
  </a-modal>
</template>
<script setup lang="ts">
  import {ref, defineProps, defineEmits, watch, onMounted} from 'vue'
  import {add,edit} from '@/api/article/category.ts'

  const props = defineProps(['row','modelValue']);

  const emits = defineEmits(['update:modelValue','success']);
  const generateFromModel = ()=>{
    return{
        id: 0,
        name: '',
        sort: 0,
    }
  }

  const fromModel = ref(generateFromModel());
  const open = ref(false)
  const confirmLoading = ref(false);
  const formRef = ref();

  const rules = {
     name: [
       { required: true, message: '分类名称不能为空', trigger: 'blur' }
     ]
      }
  const close = ()=>{
    fromModel.value = generateFromModel();
    confirmLoading.value = false;
    emits('update:modelValue',false)
  }
  const handleOk = ()=>{
    formRef.value
        .validate()
        .then(async () => {
          confirmLoading.value = true;
          if (fromModel.value.id){
            await edit(fromModel.value);
          }else {
            await add(fromModel.value)
          }
          confirmLoading.value = false;
          emits('success')
        })
        .catch(error => {
          confirmLoading.value = false;
          console.log('error', error);
        })
  }

  watch(()=>props.row,(value)=>{
    if(value){
      fromModel.value = value;
    }
  }, {
    immediate:true,
    deep:true
  })
  watch(()=>props.modelValue,(value)=>{
    open.value = value;
  },{
      immediate:true
  })
  onMounted(()=>{

  })
</script>
<style scoped lang="scss">

</style>
